package com.alibaba.otter.canal.client.adapter.support;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.function.Function;

/**
 * 执行该目标时报错 Failed to execute goal 找不到符号
 * 符号:   类 MysqlConnectionUtil
 * 位置: 程序包 com.alibaba.otter.canal.client.adapter.support
 * 大概是因为仅在launcher模块执行mvn install而这个类在common模块
 *
 * 使用Druid data source，从数据库查询数据
 * 因为launcher模块没有druid依赖，所以写到common模块里
 * 其实好像没有关系，因为launcher模块有依赖common模块
 */
public class MysqlConnectionUtil {

    public static DataSource getDataSource(){
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://10.100.50.14:3309/canal_tsdb?serverTimezone=UTC";
        String username = "root";
        String password = "123456";

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    public static Object getRS(DataSource ds, String sql, Function<ResultSet,Object> fun){
        try(Connection conn=ds.getConnection()){
            try(Statement stat = conn.createStatement()){
                try(ResultSet rs = stat.executeQuery(sql)){
                    return fun.apply(rs); // 将result set 返回出去
                }
            }
        }catch (Exception e){
            // 需要一个return 或者 throw
            System.out.println("something wrong with getting result set");
            throw new RuntimeException(e);
        }
    }
}
